﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MoleculeViewer.DAO;
using SpringGraph;
using MoleculeViewer.Entities;

namespace MoleculeViewer
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            ListBoxMolecules.ItemsSource = new List<string>()
            {
                "accholine",
                "adenosine",
                "adrenalin",
                "dopamine",
                "glutamate"
            };
            ListBoxMolecules.SelectedIndex = 0;
        }

        private void ListBoxMolecules_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listbox = sender as ListBox;

            if (listbox.SelectedItem != null)
            {
                MoleculeDAO dao = new MoleculeDAO();
                dao.GetMoleculeCompleted += new EventHandler<GetMoleculeEventArgs>(dao_GetMoleculeCompleted);
                dao.GetMolecule(listbox.SelectedItem.ToString());
            }
        }

        void dao_GetMoleculeCompleted(object sender, GetMoleculeEventArgs e)
        {
            Graph g = new Graph();

            foreach (var atom in e.Molecule.Atoms)
            {
                g.Add(new Item() { DataContext = atom });
            }

            foreach (var bond in e.Molecule.Bonds)
            {
                var atomFrom = g.Nodes.Single(item => ((Atom)item.DataContext).Id == bond.IdFrom);
                var atomTo = g.Nodes.Single(item => ((Atom)item.DataContext).Id == bond.IdTo);

                g.Link(atomFrom, atomTo);
            }

            Graph.DataProvider = g;
        }
    }
}
